package com.my.test.thread.conditition.waitandnotify;

import java.util.concurrent.atomic.AtomicInteger;

public class TestWaitNotify {

    private static Object lock = new Object();

    // flag 实际场景中是某个条件，比如队列为空，库存等
    private static boolean flag = true;

    // 仓库容量为10
    private static AtomicInteger stock = new AtomicInteger(1);


    public static void getWait() {

        new Thread(() -> {

            synchronized (lock) {
                // 当仓储容量为10认为满了，阻塞等待
                while (true) {
                    while (stock.get() == 10) {
                        try {
                            Thread.sleep(2000);
                            // 阻塞等待
                            lock.wait();
                        } catch (InterruptedException e) {
                            e.printStackTrace();
                        }
                    }
                    // 干其他事情
                    stock.incrementAndGet();
                    System.out.println("生产者:" + Thread.currentThread().getName() + " " + stock.get());
                }
            }
        }).start();

    }

    public static void getNotifall() {
        new Thread(() -> {
            synchronized (lock) {
                while (true) {
                    System.out.println("消费者: " + Thread.currentThread().getName() + " " + stock.get());
                    stock.decrementAndGet();
                    lock.notify();
                }
            }
        }).start();

    }


    public static void main(String[] args) {
        getWait();
        getNotifall();
    }

}
